﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace SlideShowGenerator.Data
{
    /// <summary>
    /// 
    /// </summary>
    public static class ImageResizer
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="outSavePath"></param>
        /// <param name="maxSideSize"></param>
        /// <param name="inputPath"></param>
        public static void ResizeImage(string outSavePath, int maxSideSize, string inputPath)
        {
            using (FileStream stream = new FileStream(inputPath, FileMode.Open))
            {
                ResizeFromStream(outSavePath, maxSideSize, stream);
            }
        }

        /// <summary>
        /// Resizes to a **SMALLER** size.
        /// </summary>
        /// <param name="outSavePath"></param>
        /// <param name="size"></param>
        /// <param name="inStream"></param>
        public static void ResizeFromStream(string outSavePath, int size, Stream inStream)
        {
            using (Image orgImg = Image.FromStream(inStream))
            {
                ImageFormat imgFmt = orgImg.RawFormat;
                int curSize = Math.Max(orgImg.Width, orgImg.Height);
                int newWidth = orgImg.Width;
                int newHeight = orgImg.Height;
                if (curSize > size)
                {
                    double sizeFactor = size / (double)curSize;
                    newWidth = Convert.ToInt32(sizeFactor * orgImg.Width);
                    newHeight = Convert.ToInt32(sizeFactor * orgImg.Height);
                }

                using (Bitmap newImg = new Bitmap(orgImg, newWidth, newHeight))
                {
                    newImg.Save(outSavePath, imgFmt);
                }
            }
        } 
    }
}
